package org.jeecg.modules.sggg.controller;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.config.StaticConfig;
import org.jeecg.modules.sggg.entity.SgGlucoseRecord;
import org.jeecg.modules.sggg.entity.SgMember;
import org.jeecg.modules.sggg.entity.SgSms;
import org.jeecg.modules.sggg.service.ISgGlucoseRecordService;
import org.jeecg.modules.sggg.service.ISgMemberService;
import org.jeecg.modules.sggg.service.ISgSmsService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;
import org.jeecg.modules.wechatSendMessage.TemplateData;
import org.jeecg.modules.wechatSendMessage.WxMssVo;
import org.jeecg.modules.wechatSendMessage.subscribeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 血糖记录表
 * @Author: jeecg-boot
 * @Date: 2022-10-17
 * @Version: V1.0
 */
@Api(tags = "血糖记录表")
@RestController
@RequestMapping("/sggg/sgGlucoseRecord")
@Slf4j
public class SgGlucoseRecordController extends JeecgController<SgGlucoseRecord, ISgGlucoseRecordService> {

    @Autowired
    private ISgGlucoseRecordService sgGlucoseRecordService;

    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysBaseApiImpl sysBaseApi;

    @Autowired
    private subscribeMessage subscribeMessage;

    @Autowired
    private SgOperationRecordsController sgOperationRecordsController;

    @Autowired
    private ISgSmsService sgSmsService;

    @Autowired
    private ISysDepartService sysDepartController;

    private static final Integer FOLLOW_EMPTY_110 = 110;

    private static final Integer GENERIC_0 = 0;

    private static final Integer GENERIC_1 = 1;

    /**
     * 血糖记录表-分页列表查询
     *
     * @param sgGlucoseRecord
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<SgGlucoseRecord>> queryPageList(SgGlucoseRecord sgGlucoseRecord,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Page<SgGlucoseRecord> page = new Page<>(pageNo, pageSize);

        List<SysRole> roleList = sysRoleService.getUserRole(sysUser.getId());
        String code;
        StringBuilder sb = new StringBuilder();
        for (SysRole role : roleList) {
            sb.append(role.getRoleCode());
            sb.append(",");
        }
        String sbstr = sb.toString();
        if (sbstr.contains("admin")) {
            code = "admin";
        } else if (sbstr.contains("dept_manage")) {
            // 机构管理员
            code = "dept_manage";
        } else {
            code = "other";
        }

        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgGlucoseRecord.setResponsibleAgencies(responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgGlucoseRecord.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }


        IPage<SgGlucoseRecord> pageList = sgGlucoseRecordService.queryList(page, sysUser.getOrgCode(),
                sgGlucoseRecord, code, sysUser.getId());
        return Result.OK(pageList);
    }

    /**
     * 查询居民血糖测量记录列表
     *
     * @param member_id
     * @return
     */
    @GetMapping(value = "/queryByMemberIdList")
    public Result<List<SgGlucoseRecord>> queryByMemberIdList(@RequestParam(name = "member_id") String member_id) {
        QueryWrapper<SgGlucoseRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", member_id);
        queryWrapper.orderByDesc("measuring_time");
        List<SgGlucoseRecord> pageList = sgGlucoseRecordService.list(queryWrapper);
        if (pageList == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(pageList);
    }

    /**
     * 居民详情列表 监测记录
     *
     * @param mid      居民id
     * @param pageNo   当前页
     * @param pageSize 页大小
     * @return 当前页数据
     */
    @GetMapping("/queryListByMid")
    public Result<IPage<SgGlucoseRecord>> queryListByMid(String mid,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgGlucoseRecord> page = new Page<>(pageNo, pageSize);
        IPage<SgGlucoseRecord> pageList = sgGlucoseRecordService.page(page, new QueryWrapper<SgGlucoseRecord>().eq("member_id", mid).orderByDesc("measuring_time"));
        return Result.OK(pageList);
    }

    /**
     * 居民详情列表 干预记录
     *
     * @param mid 居民id
     * @return 数据
     */
    @GetMapping("/interveneListByMid")
    public Result<List<SgGlucoseRecord>> interveneListByMid(String mid) {
        return Result.OK(sgGlucoseRecordService.list(
                new QueryWrapper<SgGlucoseRecord>()
                        .eq("member_id", mid)
                        .eq("intervene", 2)
                        .select("id", "intervene_content", "intervene_time", "intervene_user")
        ));
    }

    /**
     * 医生预警列表
     *
     * @param
     * @param pageNo   当前页
     * @param pageSize 页大小
     * @return 当前页数据
     */
    @GetMapping("/queryListByDoctor")
    public Result<IPage<SgGlucoseRecord>> queryListByDoctor(String name, String phone,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgGlucoseRecord> page = new Page<>(pageNo, pageSize);

        // 获取当前登录人的信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当前用户的
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        List<String> responsibleAgencies = new ArrayList<>();
        // 根据DeptAttr机构属性判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {

            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                sysUser.setOrgCode(sysUser1.getOrgCode());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
            }
        } else if (roleCode.contains("dept_manage") || roleCode.contains("admin")) {
            sysUser.setOrgCode(sysUser1.getOrgCode());

        } else {
            sysUser.setOrgCode(sysUser1.getOrgCode());
        }
        IPage<SgGlucoseRecord> pageList = sgGlucoseRecordService.queryListByDoctor(page, name, phone, responsibleAgencies, sysUser.getOrgCode(), roleCode, sysUser.getId(), "0");
        return Result.OK(pageList);
    }

    /**
     * 查询居民待干预测量记录列表
     *
     * @param member_id
     * @return
     */
    @GetMapping(value = "/queryByIdIntervene")
    public Result<List<SgGlucoseRecord>> queryByIdIntervene(@RequestParam(name = "member_id") String member_id) {
        List<SgGlucoseRecord> sgGlucoseRecords = sgGlucoseRecordService.list(new QueryWrapper<SgGlucoseRecord>().eq("member_id", member_id).eq("intervene", 0).orderByDesc("measuring_time"));
        if (sgGlucoseRecords == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgGlucoseRecords);
    }

    /**
     * 血糖记录表-添加
     *
     * @param gr
     * @return
     * @throws Exception
     */
    @AutoLog(value = "血糖记录表-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SgGlucoseRecord gr) throws Exception {
        /**
         * 空腹
         * 凌晨、早餐前、午餐前、晚餐前 低血糖<3.9mmp/L 高血糖>6.1mmo/l
         * <p>
         * 餐后
         * 早餐后、午餐后、晚餐后  高血糖>=7.8mmo/l
         */
        synchronized (gr.getMemberId()) {
            switch (gr.getPhase()) {
                case 0:
                case 1:
                case 3:
                case 5:// 空腹
                    if (gr.getGluval() < 3.9) {
                        gr.setLevel(1); // 低血糖
                    } else if (gr.getGluval() > 6.1) {
                        gr.setLevel(2); // 高血糖
                    } else {
                        gr.setLevel(0); // 正常
                    }
                    break;
                case 2:
                case 4:
                case 6: // 餐后
                    if (gr.getGluval() >= 7.8) {
                        gr.setLevel(2); // 高血糖
                    } else {
                        gr.setLevel(0); // 正常
                    }
            }

            // 判断是否干预
            SgMember m = sgMemberService.getById(gr.getMemberId());
            if (m != null && m.getSugarMax() != null && m.getSugarMin() != null) {
                gr.setIntervene(gr.getGluval() >= m.getSugarMax() || gr.getGluval() <= m.getSugarMin() ? 0 : 1);
            } else {
                gr.setIntervene(1);
            }

            // 发送预警短信
            try {
                if (gr.getIntervene() == 0) {
                    SgMember sgMember = sgMemberService.getById(gr.getMemberId());
                    SysUser user = sysUserService.getById(sgMember.getDoctorId());
                    String route = "<a target='_blank' href='/sggg/member/" + gr.getMemberId() + "'>点击查看详情</a>";
                    MessageDTO messageDTO = new MessageDTO(sgMember.getName(), user.getUsername(), "患者血糖测量超出预警提醒", "您好,您所管辖的三高患者:" + sgMember.getName() + ",身份证号:" + sgMember.getPhone() + ",手机号:" + sgMember.getPhone() + ",在" + DateTime.now() + "测量血糖数据时超出预警,请您及时查看情况!" + route, "1");
                    sysBaseApi.sendSysAnnouncement(messageDTO);
                }
                // 健康任务
                sgOperationRecordsController.dailyMeasurementTask("医防融合设备使用", 1, m.getId());
            } catch (Exception e) {
                log.info("血糖测量预警推送异常！原因 => {}", e.getMessage());
            } finally {
                sgGlucoseRecordService.save(gr);
            }
            return Result.OK("添加成功！");
        }
    }

    /**
     * 血糖记录表-编辑
     *
     * @param sgGlucoseRecord
     * @return
     */
    @AutoLog(value = "血糖记录表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SgGlucoseRecord sgGlucoseRecord) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        sgGlucoseRecord.setInterveneTime(DateTime.now());
        sgGlucoseRecord.setInterveneUser(sysUser.getId());
        sgGlucoseRecord.setMemberName(null);
        sgGlucoseRecord.setMemberPhone(null);
        sgGlucoseRecord.setIdCard(null);
        sgGlucoseRecord.setSex(null);
        sgGlucoseRecord.setAvatar(null);
        sgGlucoseRecord.setDoctorName(null);
        sgGlucoseRecord.setThreeTag(null);
        sgGlucoseRecord.setSugarWarning(null);
        sgGlucoseRecordService.updateById(sgGlucoseRecord);
        return Result.OK("编辑成功!");
    }

    /**
     * 血糖记录表-通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "血糖记录表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id") String id) {
        sgGlucoseRecordService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 血糖记录表-批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "血糖记录表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids") String ids) {
        this.sgGlucoseRecordService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 血糖记录表-通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "血糖记录表-通过id查询", notes = "血糖记录表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SgGlucoseRecord> queryById(@RequestParam(name = "id") String id) {
        SgGlucoseRecord sgGlucoseRecord = sgGlucoseRecordService.getById(id);
        if (sgGlucoseRecord == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgGlucoseRecord);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sgGlucoseRecord
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SgGlucoseRecord sgGlucoseRecord) {
        return super.exportXls(request, sgGlucoseRecord, SgGlucoseRecord.class, "血糖记录表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SgGlucoseRecord.class);
    }

    /**
     * 通过id查询用户全天血糖检测记录
     *
     * @param memberId 居民id
     * @return 通过id查询用户全天血糖检测记录
     */
    @GetMapping("/getGlucoseRecord")
    public Result<JSONArray> getGlucoseRecord(String memberId) {
        JSONArray jsonArray = new JSONArray();

        List<SgGlucoseRecord> glucoseRecordList = sgGlucoseRecordService.getGlucoseRecord(memberId);
        // 根据测量日期进行分组
        Map<String, List<SgGlucoseRecord>> maps = glucoseRecordList.stream().collect(Collectors.groupingBy(SgGlucoseRecord::getRecordDay));

        Set<String> setKey = maps.keySet();
        for (String s : setKey) {
            Map<String, Object> map = new HashMap<>();
            map.put("data", s);

            List<SgGlucoseRecord> value = maps.get(s);

            for (SgGlucoseRecord sgGlucoseRecord : value) {
                JSONObject levelObject = new JSONObject();
                levelObject.put("gluval", sgGlucoseRecord.getGluval());
                levelObject.put("level", sgGlucoseRecord.getLevel());
                levelObject.put("time", sgGlucoseRecord.getRecordTime());

                if (sgGlucoseRecord.getPhase() == 0) {
                    map.put("lc", levelObject);
                }
                if (sgGlucoseRecord.getPhase() == 1) {
                    map.put("zcq", levelObject);
                }
                if (sgGlucoseRecord.getPhase() == 2) {
                    map.put("zch", levelObject);
                }
                if (sgGlucoseRecord.getPhase() == 3) {
                    map.put("wcq", levelObject);
                }
                if (sgGlucoseRecord.getPhase() == 4) {
                    map.put("wch", levelObject);
                }
                if (sgGlucoseRecord.getPhase() == 5) {
                    map.put("dinnerq", levelObject);
                }
                if (sgGlucoseRecord.getPhase() == 6) {
                    map.put("dinnerh", levelObject);
                }
                if (sgGlucoseRecord.getPhase() == 7) {
                    map.put("sq", levelObject);
                }

            }

            if (map.size() != 8) {
                if (!(map.containsKey("lc"))) {
                    Map<String, Object> m = new HashMap<>();
                    m.put("gluval", "");
                    m.put("level", "");
                    m.put("time", "");
                    map.put("lc", m);
                }
                if (!(map.containsKey("zcq"))) {
                    Map<String, Object> m = new HashMap<>();
                    m.put("gluval", "");
                    m.put("level", "");
                    m.put("time", "");
                    map.put("zcq", m);
                }
                if (!(map.containsKey("zch"))) {
                    Map<String, Object> m = new HashMap<>();
                    m.put("gluval", "");
                    m.put("level", "");
                    m.put("time", "");
                    map.put("zch", m);
                }
                if (!(map.containsKey("wcq"))) {
                    Map<String, Object> m = new HashMap<>();
                    m.put("gluval", "");
                    m.put("level", "");
                    m.put("time", "");
                    map.put("wcq", m);
                }
                if (!(map.containsKey("wch"))) {
                    Map<String, Object> m = new HashMap<>();
                    m.put("gluval", "");
                    m.put("level", "");
                    m.put("time", "");
                    map.put("wch", m);
                }
                if (!(map.containsKey("dinnerq"))) {
                    Map<String, Object> m = new HashMap<>();
                    m.put("gluval", "");
                    m.put("level", "");
                    m.put("time", "");
                    map.put("dinnerq", m);
                }
                if (!(map.containsKey("dinnerh"))) {
                    Map<String, Object> m = new HashMap<>();
                    m.put("gluval", "");
                    m.put("level", "");
                    m.put("time", "");
                    map.put("dinnerh", m);
                }
                if (!(map.containsKey("sq"))) {
                    Map<String, Object> m = new HashMap<>();
                    m.put("gluval", "");
                    m.put("level", "");
                    m.put("time", "");
                    map.put("sq", m);
                }
            }
            jsonArray.add(map);
        }
        return Result.OK(jsonArray);
    }

    /**
     * 通过id统计血糖监测记录
     */
    @GetMapping(value = "/getGlucoseStatistics")
    public Result<Map<String, Object>> getGlucoseStatistics(String memberId) {
        NumberFormat percentInstance = NumberFormat.getPercentInstance();
        // 设置保留几位小数，这里设置的是保留两位小数
        percentInstance.setMinimumFractionDigits(2);

        int total = this.sgGlucoseRecordService.getGlucoseStatistics(memberId, null);

        int normal = this.sgGlucoseRecordService.getGlucoseStatistics(memberId, 0);
        Map<String, Object> normalMap = new HashMap<>();
        normalMap.put("num", normal);
        normalMap.put("avg", percentInstance.format((float) normal / (float) total));

        int first = this.sgGlucoseRecordService.getGlucoseStatistics(memberId, 1);
        Map<String, Object> firstMap = new HashMap<>();
        firstMap.put("num", first);
        firstMap.put("avg", percentInstance.format((float) first / (float) total));

        int second = this.sgGlucoseRecordService.getGlucoseStatistics(memberId, 2);
        Map<String, Object> secondMap = new HashMap<>();
        secondMap.put("num", second);
        secondMap.put("avg", percentInstance.format((float) second / (float) total));

        Map<String, Object> map = new HashMap<>();
        map.put("count", total);
        map.put("normal", normalMap);
        map.put("low", firstMap);
        map.put("high", secondMap);

        return Result.OK(map);
    }


    /**
     * 通过日期统计血糖监测记录
     *
     * @param memberId
     * @param dateStartTime
     * @param dateEndTime
     * @return
     */
    @GetMapping(value = "/getGlucoseStatisticsByDate")
    public Result<Map<String, Object>> getGlucoseStatisticsByDate(String memberId, String dateStartTime, String dateEndTime) {
        SgGlucoseRecord byDate = this.sgGlucoseRecordService.getGlucoseStatisticsByDate(memberId, dateStartTime, dateEndTime);
        Map<String, Object> map = new HashMap<>();
        if (byDate != null) {
            map.put("gluvalAvg", byDate.getGluvalAvg());
            map.put("gluvalMax", byDate.getGluvalMax());
            map.put("gluvalMin", byDate.getGluvalMin());
        } else {
            map.put("gluvalAvg", 0);
            map.put("gluvalMax", 0);
            map.put("gluvalMin", 0);
        }

        return Result.OK(map);
    }


    /**
     * 通过id统计血糖监测记录平均值
     *
     * @param memberId
     * @return
     */
    @GetMapping(value = "/getGlucoseStatisticsAvg")
    public Result<Map<String, Object>> getGlucoseStatisticsAvg(String memberId) {

        // 凌晨
        Double lcAvg = this.sgGlucoseRecordService.getGlucoseStatisticsAvg(memberId, 0);
        // 餐前
        Double cqAvg = this.sgGlucoseRecordService.getGlucoseStatisticsAvg(memberId, 1);
        // 餐后
        Double chAvg = this.sgGlucoseRecordService.getGlucoseStatisticsAvg(memberId, 2);
        // 睡前
        Double sqAvg = this.sgGlucoseRecordService.getGlucoseStatisticsAvg(memberId, 3);

        Map<String, Object> map = new HashMap<>();
        map.put("lc", lcAvg);
        map.put("cq", cqAvg);
        map.put("ch", chAvg);
        map.put("sq", sqAvg);

        return Result.OK(map);
    }

    /**
     * 通过id统计血糖监测记录餐前餐后平均值
     *
     * @param memberId
     * @return
     */
    @GetMapping(value = "/getGlucoseStatisticsById")
    public Result<Map<String, Object>> getGlucoseStatisticsById(String memberId) {
        // 早餐前
        Double breakfastBefore = this.sgGlucoseRecordService.getGlucoseStatisticsById(memberId, 1);
        // 早餐后
        Double breakfastAfter = this.sgGlucoseRecordService.getGlucoseStatisticsById(memberId, 2);
        // 午餐前
        Double lunchBefore = this.sgGlucoseRecordService.getGlucoseStatisticsById(memberId, 3);
        // 午餐后
        Double lunchAfter = this.sgGlucoseRecordService.getGlucoseStatisticsById(memberId, 4);
        // 晚餐前
        Double dinnerBefore = this.sgGlucoseRecordService.getGlucoseStatisticsById(memberId, 5);
        // 晚餐后
        Double dinnerAfter = this.sgGlucoseRecordService.getGlucoseStatisticsById(memberId, 6);

        Map<String, Object> map = new HashMap<>();
        map.put("breakfastBefore", breakfastBefore);
        map.put("breakfastAfter", breakfastAfter);
        map.put("lunchBefore", lunchBefore);
        map.put("lunchAfter", lunchAfter);
        map.put("dinnerBefore", dinnerBefore);
        map.put("dinnerAfter", dinnerAfter);


        return Result.OK(map);
    }

    /**
     * 测量超出预警，给关联人发送短信
     *
     * @param member
     * @param glucoseRecord
     * @throws Exception
     */
    public void sendSms(SgMember member, SgGlucoseRecord glucoseRecord) throws Exception {
        JSONObject obj = new JSONObject();
        String type = glucoseRecord.getLevel() == 1 ? "偏低" : glucoseRecord.getLevel() == 2 ? "偏高" : "正常";
        // 给居民发
        if (member.getPhone() != null) {
            SgSms sms = sgSmsService.getOne(new QueryWrapper<SgSms>().eq("sys_org_code", member.getSysOrgCode()).eq("sms_type", 0));
            if (sms != null) {
                String[] params = sms.getTemplateParam().split(",");
                for (String param : params) {
                    if (param.equals("type")) {
                        obj.put("type", "血糖结果");
                    } else if (param.equals("values")) {
                        obj.put("values", glucoseRecord.getGluval() + "mmol/L");
                    }
                }
                DySmsEnum.MEASUREMENT_WARNING_TEMPLATE_CODE.setTemplateCode(sms.getTemplateCode());
                DySmsEnum.MEASUREMENT_WARNING_TEMPLATE_CODE.setSignName(sms.getSignName());
                DySmsEnum.MEASUREMENT_WARNING_TEMPLATE_CODE.setKeys(sms.getTemplateParam());
                JSONObject accessKey = new JSONObject();
                accessKey.put("accessKeyId", sms.getAccessKey());
                accessKey.put("accessKeySecret", sms.getSecretKey());
                DySmsHelper.sendSms(member.getPhone(), obj, DySmsEnum.MEASUREMENT_WARNING_TEMPLATE_CODE, accessKey);
            }
        }
        // 给紧急联系人发
        if (member.getUrgentPhone() != null) {
            SgSms sms = sgSmsService.getOne(new QueryWrapper<SgSms>().eq("sys_org_code", member.getSysOrgCode()).eq("sms_type", 1));
            if (sms != null) {
                String[] params = sms.getTemplateParam().split(",");
                for (String param : params) {
                    switch (param) {
                        case "name":
                            obj.put("name", member.getName());
                            break;
                        case "type":
                            obj.put("type", "血糖");
                            break;
                        case "values":
                            obj.put("values", glucoseRecord.getGluval() + "mmol/L，" + "测量结果" + type);
                            break;
                    }
                }
                DySmsEnum.EMERGENCY_CONTACT_TEMPLATE_CODE.setTemplateCode(sms.getTemplateCode());
                DySmsEnum.EMERGENCY_CONTACT_TEMPLATE_CODE.setSignName(sms.getSignName());
                DySmsEnum.EMERGENCY_CONTACT_TEMPLATE_CODE.setKeys(sms.getTemplateParam());
                JSONObject accessKey = new JSONObject();
                accessKey.put("accessKeyId", sms.getAccessKey());
                accessKey.put("accessKeySecret", sms.getSecretKey());
                DySmsHelper.sendSms(member.getPhone(), obj, DySmsEnum.EMERGENCY_CONTACT_TEMPLATE_CODE, accessKey);
            }
        }
        // 发送订阅消息
        if (member.getOpenId() != null) {
            StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class);
            // 订阅消息参数
            WxMssVo wxMssVo = new WxMssVo();
            wxMssVo.setTouser(member.getOpenId());
            wxMssVo.setTemplate_id(staticConfig.getSUGAR_MEA_EXCE_REMIND());
            Map<String, TemplateData> m = new HashMap<>(4);
            m.put("thing1", new TemplateData(glucoseRecord.getGluval().toString()));
            m.put("thing2", new TemplateData(type));
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            m.put("time3", new TemplateData(formatter.format(glucoseRecord.getMeasuringTime())));
            wxMssVo.setData(m);
            subscribeMessage.send(wxMssVo);
        }
    }


}
